package runthrad;

import javax.xml.bind.DatatypeConverter;
import java.io.FileInputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;

/**
 * @author lianmingzhang
 * @create 2017-09-11 下午9:25
 */
public class DigestThread extends Thread {
    private String filename;
    private byte[] digest;

    public DigestThread(String filename) {
        this.filename = filename;
    }

    public void run() { //将指定文件计算一个256位的SHA-2消息摘要。
        try {
            FileInputStream in = new FileInputStream(filename);
            MessageDigest sha = MessageDigest.getInstance("SHA-256");
            DigestInputStream din = new DigestInputStream(in, sha);
            while(din.read() != -1) ;
            din.close();

            digest = sha.digest();

            StringBuilder result = new StringBuilder(filename);
            result.append(": ");
            result.append(DatatypeConverter.printHexBinary(digest));
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public byte[] getDigest() {
        return digest;
    }
}
